package com.zghl.controller;

import com.zghl.pojo.Area;
import com.zghl.pojo.Unit;
import com.zghl.pojo.vo.AreaVo;
import com.zghl.service.AreaService;
import com.zghl.service.UnitService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/area")
public class AreaController {

    @Resource
    private AreaService areaService;
    @Resource
    private UnitService unitService;

    @RequestMapping("/getList")
    public ModelAndView getList(){
        List<AreaVo> areaVos = areaService.areaList(null);

        ModelAndView modelAndView=new ModelAndView();

        modelAndView.setViewName("areaList");
        modelAndView.addObject("list",areaVos);

        return modelAndView;
    }

    @RequestMapping("/add")
    public ModelAndView add(){
        List<Unit> units = unitService.UnitList(null);

        Area area=new Area();

        ModelAndView modelAndView=new ModelAndView();

        modelAndView.setViewName("areaAdd");
        modelAndView.addObject("area",area);
        modelAndView.addObject("un",units);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/save")
    public ModelAndView save(@ModelAttribute Area area){

        Integer integer = areaService.addByArea(area);

        if (integer>0){
            return getList();
        }
        throw  new RuntimeException("添加错误");
    }

    @RequestMapping("/delete/{Id}")
    public ModelAndView deleteUnit(@PathVariable("Id") int Id){
        Integer integer =areaService.deleteByArea(Id);

        if (integer>0){
            return getList();
        }
        throw  new RuntimeException("删除错误");
    }

    @RequestMapping("/update/{Id}")
    public ModelAndView update(@PathVariable("Id") int Id){
        Map<String,Object> map=new HashMap<>();

        map.put("id",Id);

        List<Area> areas = areaService.List(map);
        List<Unit> units = unitService.UnitList(null);

        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("areaUpdate");

        Area area=new Area();

        for (Area a:areas) {
            BeanUtils.copyProperties(a,area);
        }
        modelAndView.addObject("a",area);
        modelAndView.addObject("u",units);
        modelAndView.addObject("id",Id);
        return modelAndView;
    }

    @ResponseBody
    @RequestMapping("/updateSvae/{Id}")
    public ModelAndView updateUnit(@PathVariable("Id") int Id,@ModelAttribute Area area){
        Area area1=new Area();

        BeanUtils.copyProperties(area,area1);
        area1.setId(Id);

        Integer integer = areaService.updateByArea(area1);
        if (integer>0){
            return getList();
        }
        throw  new RuntimeException("修改错误");
    }
}
